package com.rocky.study.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {

    private static Semaphore semaphore = new Semaphore(1);

    public static void main(String[] args) {
        Runnable run = () -> {
            boolean isAcquired = false;
            try {
                semaphore.acquire(); // state - 1
                System.out.println(Thread.currentThread().getName() + "获取令牌====");
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println(Thread.currentThread().getName() + "释放令牌====");
                semaphore.release();
                System.out.println(Thread.currentThread().getName() + "剩余令牌====" + semaphore.availablePermits());
            }
        };

        Thread t1 = new Thread(run,"t1");
        Thread t2 = new Thread(run,"t2");
        Thread t3 = new Thread(run,"t3");
        t1.start();
        t2.start();
        t3.start();
        t2.interrupt();
        t3.interrupt();
    }

}
